<template>
  <div class="admin-dashboard">
    <h2>管理中心</h2>
    <p>欢迎进入智能健身衣管理后台。可查看用户数据、设备状态、统计报表等。</p>

    <!-- 用户数据 -->
    <div class="admin-section">
      <h3>用户数据</h3>
      <table>
        <thead>
          <tr>
            <th>用户名</th>
            <th>邮箱</th>
            <th>角色</th>
            <th>状态</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.id">
            <td>{{ user.username }}</td>
            <td>{{ user.email }}</td>
            <td>{{ user.role }}</td>
            <td>
              <span :style="{ color: user.status ? 'green' : 'red' }">
                {{ user.status ? '活跃' : '禁用' }}
              </span>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 用户分页控件 -->
      <div class="pagination">
        <button @click="prevUserPage" :disabled="userCurrentPage === 1">上一页</button>
        <span>第 {{ userCurrentPage }} / {{ userTotalPages }} 页</span>
        <button @click="nextUserPage" :disabled="userCurrentPage === userTotalPages">下一页</button>
        <button @click="fetchData" style="margin-left: 1rem;">刷新</button>
      </div>
    </div>

    <!-- 设备状态 -->
    <div class="admin-section">
      <h3>设备状态</h3>

      <table>
        <thead>
          <tr>
            <th>设备ID</th>
            <th>状态</th>
            <th>绑定用户</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="device in devices" :key="device.id">
            <td>{{ device.id }}</td>
            <td>
              <span :style="{ color: device.status ? 'green' : 'red' }">
                {{ device.status ? '使用中' : '空闲中' }}
              </span>
            </td>
            <td>{{ device.openid !== '0' ? device.openid : '暂无' }}</td>
          </tr>
        </tbody>
      </table>

      <!-- 分页控件 -->
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span>第 {{ currentPage }} / {{ totalPages }} 页</span>
        <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
        <button @click="fetchData" style="margin-left: 1rem;">刷新</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 用户相关
const users = ref([])
const userCurrentPage = ref(1)
const userPageSize = ref(10)
const userTotalItems = ref(0)

// 计算用户总页数
const userTotalPages = computed(() => Math.ceil(userTotalItems.value / userPageSize.value))

// 设备相关
const devices = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)

// 计算设备总页数
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

/**
 * 获取用户总数（用于计算总页数）
 */
async function fetchUserTotalCount() {
  const res = await fetch('http://47.108.221.119:5000/getusercount')
  if (res.ok) {
    const data = await res.json()
    userTotalItems.value = data.count
  } else {
    console.error('获取用户总数失败')
  }
}

/**
 * 获取用户列表（GET），支持分页
 */
async function fetchUsers(page = 1, size = 10) {
  const res = await fetch(`http://47.108.221.119:5000/getwebuser?page=${page}&size=${size}`)
  if (res.ok) {
    const data = await res.json()
    users.value = data
  } else {
    console.error('获取用户列表失败')
  }
}

/**
 * 获取设备总数（用于计算总页数）
 */
async function fetchTotalCount() {
  const res = await fetch('http://47.108.221.119:5000/getdevicecount')
  if (res.ok) {
    const data = await res.json()
    totalItems.value = data.count
  } else {
    console.error('获取设备总数失败')
  }
}

/**
 * 获取设备列表（GET）
 */
async function fetchDevices(page = 1, size = 10) {
  const res = await fetch(`http://47.108.221.119:5000/getdevicelist?page=${page}&size=${size}`)
  if (res.ok) {
    const data = await res.json()
    devices.value = data
  } else {
    console.error('获取设备失败')
  }
}

/**
 * 加载所有数据
 */
 async function fetchData() {
  try {
    // 等待所有异步请求完成
    await Promise.all([
      fetchUserTotalCount(),
      fetchTotalCount()
    ]);

    // 在获取到总数之后，根据当前页码获取相应的列表数据
    await Promise.all([
      fetchUsers(userCurrentPage.value, userPageSize.value),
      fetchDevices(currentPage.value, pageSize.value)
    ]);
  } catch (error) {
    console.error('数据加载过程中出现错误:', error);
  }
}

/**
 * 用户分页操作
 */
function prevUserPage() {
  if (userCurrentPage.value > 1) {
    userCurrentPage.value--
    fetchUsers(userCurrentPage.value, userPageSize.value)
  }
}

function nextUserPage() {
  if (userCurrentPage.value < userTotalPages.value) {
    userCurrentPage.value++
    fetchUsers(userCurrentPage.value, userPageSize.value)
  }
}

/**
 * 设备分页操作
 */
function prevPage() {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchDevices(currentPage.value, pageSize.value)
  }
}

function nextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchDevices(currentPage.value, pageSize.value)
  }
}

onMounted(async () => {
  await fetchData()
})
</script>

<style scoped>
.admin-dashboard {
  padding: 2rem;

}
.admin-section {
  margin-top: 2rem;
  background: #f6f8fa;
  padding: 1rem;
  border-radius: 8px;
  color: #000; /* 表头字体设为黑色 */
}
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 1rem;
  color: #000; /* 表头字体设为黑色 */
}
th, td {
  border: 1px solid #ddd;
  padding: 0.5rem;
  text-align: left;
  color: #000; /* 表格内容字体设为黑色 */
}
th {
  background: #e3f2fd;
  color: #000; /* 表头字体设为黑色 */
}
.pagination {
  margin-top: 1rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  color: #000; /* 表头字体设为黑色 */
}
button[disabled] {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>